<template>
  <div class="tasks-page">
    <div class="page-header">
      <div class="header-left">
        <h1>任务管理</h1>
        <p>管理您的所有任务</p>
      </div>
    </div>
    
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="任务描述">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入任务描述"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" :value="undefined" />
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 任务列表 -->
    <el-card class="task-list-card">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="tasks.length === 0" class="empty-state">
        <el-empty description="暂无任务数据" />
      </div>
      
      <div v-else class="task-list">
        <div
          v-for="task in tasks"
          :key="task.id"
          class="task-item"
        >
          <div class="task-content">
            <div class="task-header">
              <h4>{{ task.description }}</h4>
              <div class="task-actions">
                <el-button type="text" @click="editTask(task)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="text" @click="handleDeleteTask(task)" class="danger">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            
            <div class="task-meta">
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ task.assignedToName }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(task.beginDate) }} - {{ formatDate(task.dueDate) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Folder /></el-icon>
                <span>项目ID: {{ task.projectId }}</span>
              </div>
            </div>
            
            <div class="task-status">
              <el-tag :type="getTaskStatusType(task.status)">
                {{ getTaskStatusText(task.status) }}
              </el-tag>
              <span v-if="task.actualEndDate" class="completion-time">
                完成于 {{ formatDate(task.actualEndDate) }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalCount > 0" class="pagination-container">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑任务对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑任务"
      width="80vw"
      @close="resetTaskForm"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="80px"
      >
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入任务描述"
          />
        </el-form-item>
        <el-form-item label="分配给" prop="assignedTo">
          <el-input
            v-model="taskForm.assignedToName"
            placeholder="负责人"
            disabled
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="beginDate">
          <el-date-picker
            v-model="taskForm.beginDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="截止日期" prop="dueDate">
          <el-date-picker
            v-model="taskForm.dueDate"
            type="date"
            placeholder="选择截止日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="taskForm.status" placeholder="请选择状态">
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleTaskSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getTaskList, updateTask, deleteTask, type ProjectTask, type UpdateTaskRequest } from '@/api/task'
import dayjs from 'dayjs'

const loading = ref(false)
const submitting = ref(false)
const showEditDialog = ref(false)

const tasks = ref<ProjectTask[]>([])
const totalCount = ref(0)
const editingTask = ref<ProjectTask | null>(null)

const searchForm = reactive({
  keyWord: '',
  status: undefined as number | undefined
})

const dateRange = ref<[string, string] | null>(null)

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10
})

const taskFormRef = ref<FormInstance>()
const taskForm = reactive({
  description: '',
  assignedTo: 0,
  assignedToName: '',
  beginDate: '',
  dueDate: '',
  status: 0
})

const taskRules: FormRules = {
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' },
    { max: 200, message: '任务描述不能超过200个字符', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  dueDate: [
    { required: true, message: '请选择截止日期', trigger: 'change' }
  ]
}

const fetchTasks = async () => {
  loading.value = true
  try {
    const params = {
      projectId: 0, // 获取所有项目的任务
      keyWord: searchForm.keyWord,
      status: searchForm.status,
      dueBeginTime: dateRange.value?.[0],
      dueEndTime: dateRange.value?.[1],
      isMy: true, // 只获取我的任务
      pageDto: {
        pageNumber: pagination.pageIndex,
        pageSize: pagination.pageSize
      }
    }
    
    const result = await getTaskList(params)
    tasks.value = result.data.items
    totalCount.value = result.data.totalCount
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchTasks()
}

const handleReset = () => {
  searchForm.keyWord = ''
  searchForm.status = undefined
  dateRange.value = null
  pagination.pageIndex = 1
  fetchTasks()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchTasks()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchTasks()
}

const editTask = (task: ProjectTask) => {
  editingTask.value = task
  taskForm.description = task.description
  taskForm.assignedTo = task.assignedTo
  taskForm.assignedToName = task.assignedToName
  taskForm.beginDate = task.beginDate
  taskForm.dueDate = task.dueDate
  taskForm.status = task.status
  showEditDialog.value = true
}

const handleDeleteTask = async (task: ProjectTask) => {
  try {
    await ElMessageBox.confirm('确定要删除这个任务吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteTask(task.id)
    ElMessage.success('删除成功')
    fetchTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetTaskForm = () => {
  editingTask.value = null
  taskForm.description = ''
  taskForm.assignedTo = 0
  taskForm.assignedToName = ''
  taskForm.beginDate = ''
  taskForm.dueDate = ''
  taskForm.status = 0
  taskFormRef.value?.resetFields()
}

const handleTaskSubmit = async () => {
  if (!taskFormRef.value || !editingTask.value) return
  
  try {
    const valid = await taskFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    const updateData: UpdateTaskRequest = {
      id: editingTask.value.id,
      description: taskForm.description,
      assignedTo: taskForm.assignedTo,
      beginDate: taskForm.beginDate,
      dueDate: taskForm.dueDate,
      status: taskForm.status
    }
    
    await updateTask(updateData)
    ElMessage.success('更新成功')
    showEditDialog.value = false
    fetchTasks()
  } catch (error) {
    ElMessage.error('更新失败')
  } finally {
    submitting.value = false
  }
}

const getTaskStatusType = (status: number) => {
  return status === 1 ? 'success' : 'warning'
}

const getTaskStatusText = (status: number) => {
  return status === 1 ? '已完成' : '进行中'
}

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped lang="scss">
.tasks-page {
  .page-header {
    margin-bottom: 24px;
    
    h1 {
      font-size: 28px;
      color: #333;
      margin-bottom: 8px;
    }
    
    p {
      color: #666;
      font-size: 14px;
    }
  }
  
  .filter-card {
    margin-bottom: 24px;
  }
  
  .task-list-card {
    .loading-container {
      padding: 40px 0;
    }
    
    .empty-state {
      padding: 60px 0;
    }
    
    .task-list {
      .task-item {
        border: 1px solid #e6e6e6;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 16px;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
        }
        
        .task-content {
          .task-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            
            h4 {
              font-size: 16px;
              color: #333;
              margin: 0;
              flex: 1;
            }
            
            .task-actions {
              display: flex;
              gap: 8px;
              
              .danger {
                color: #f56c6c;
                
                &:hover {
                  background-color: #fef0f0;
                }
              }
            }
          }
          
          .task-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-bottom: 12px;
            
            .meta-item {
              display: flex;
              align-items: center;
              color: #666;
              font-size: 14px;
              
              .el-icon {
                margin-right: 4px;
              }
            }
          }
          
          .task-status {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .completion-time {
              color: #52c41a;
              font-size: 12px;
            }
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

@media (max-width: 768px) {
  .task-item {
    .task-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .task-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
    
    .task-meta {
      flex-direction: column;
      gap: 8px;
    }
  }
}
</style>


